import router from '@/router/index';
import axios from 'axios';
import { ElMessage } from 'element-plus'
//  创建axios实例
// ENV判断运行环境
const ENV = process.env.NODE_ENV;
const host = ENV === 'development' ? 'http://127.0.0.1:3000' : 'http://101.201.181.175';
const service = axios.create({
  baseURL: host,
});

// 请求拦截
service.interceptors.request.use((config) => {
  if (config.url.indexOf('register') < 0 && config.url.indexOf('login') < 0) {
    config.headers.authorization = localStorage.getItem('token');
  }
  return config;
});

// 响应拦截
service.interceptors.response.use((res) => {
  const { status, message } = res.data;
  console.log(res.data);
  if (status === 200) {
    return res.data;
  } else {
    ElMessage({
      message: message,
      type: 'error',
    });
  }
  if (message === '身份认证失败') {
    const redirectUrl = router.currentRoute.value.fullPath
    router.replace(`/login?redirectUrl=${redirectUrl}`)
  }
});

//  封装请求函数
const request = (options) => {
  if (options.method === 'get') {
    options.params = options.data;
  }
  return service(options);
};

export default request;

